﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ICeFramework.Serialization
{
    public static class BinarySerialization
    {
        public static byte[] Serialize(object graph)
        {
            if (graph == null)
            {
                return null;
            }
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            try
            {
                formatter.Serialize(stream, graph);
                return stream.ToArray();
            }
            finally
            {
                stream.Close();
            }
        }

        public static object Deserialize(byte[] byteArray)
        {
            if (byteArray == null)
            {
                return null;
            }
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream(byteArray);
            try
            {
                return formatter.Deserialize(stream);
            }
            finally
            {
                stream.Close();
            }
        }

        public static byte[] GetBytes(Object o)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf1 = new BinaryFormatter();
            bf1.Serialize(ms, o);
            return ms.ToArray();
        }

        public static object GetObject(byte[] theByteArray)
        {
            MemoryStream ms = new MemoryStream(theByteArray);
            BinaryFormatter bf1 = new BinaryFormatter();
            ms.Position = 0;
            return bf1.Deserialize(ms);
        }
    }
}
